﻿using AutoTest.Business.IServices.Common;
using AutoTest.Business.Options;
using AutoTest.Domain;
using MimeKit;

namespace AutoTest.Business.Services.Common
{
    /// <summary>
    /// 邮件服务
    /// </summary>
    public class MailKitService(ISettingService settingService) : IMailKitService
    {
        private readonly ISettingService _settingService = settingService;

        /// <summary>
        ///发送邮件
        /// </summary>
        /// <param name="toAddressList">接收人</param>
        /// <param name="title">标题</param>
        /// <param name="content">内容</param>
        /// <param name="attachments">附件</param>
        /// <returns></returns>
        public async Task SendMail(List<KeyValuePair<string, string>> toAddressList, string title, string content, List<KeyValuePair<string, byte[]>>? attachments = null)
        {
            var serverInfo = await _settingService.GetSettingOptionAsync<MailkitOption>(AppConsts.APPSETTING_MAILKIT);
            SendMail(serverInfo, toAddressList, title, content, attachments);
        }

        /// <summary>
        ///发送邮件
        /// </summary>
        /// <param name="serverInfo">邮件服务器配置信息</param>
        /// <param name="toAddressList">接收人</param>
        /// <param name="title">标题</param>
        /// <param name="content">内容</param>
        /// <param name="attachments">附件</param>
        /// <returns></returns>
        public void SendMail(MailkitOption serverInfo, List<KeyValuePair<string, string>> toAddressList, string title, string content, List<KeyValuePair<string, byte[]>>? attachments = null)
        {
            var server = serverInfo.Server;
            var port = serverInfo.Port;
            var account = serverInfo.Account;
            var accountName = serverInfo.AccountName;
            var pwd = serverInfo.Pwd;

            var mailMessage = new MimeMessage();
            var fromMailAddress = new MailboxAddress(accountName, account);
            mailMessage.From.Add(fromMailAddress);
            var toMailAddress = toAddressList.Select(x => new MailboxAddress(x.Key, x.Value));
            mailMessage.To.AddRange(toMailAddress);

            var bodyBuilder = new BodyBuilder() { HtmlBody = content };
            if (attachments != null)
            {
                foreach (var item in attachments)
                {
                    bodyBuilder.Attachments.Add(item.Key, item.Value);
                }
            }
            mailMessage.Body = bodyBuilder.ToMessageBody();
            mailMessage.Subject = title;
            using var smtpClient = new MailKit.Net.Smtp.SmtpClient();
            smtpClient.Timeout = 10 * 1000;   //设置超时时间
            smtpClient.Connect(server, port, MailKit.Security.SecureSocketOptions.Auto);//连接到远程smtp服务器
            smtpClient.Authenticate(account, pwd);
            smtpClient.Send(mailMessage);//发送邮件
            smtpClient.Disconnect(true);
        }
    }
}
